<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-5-11
 * Time: 9:12
 */
namespace app\common\model;

use AlibabaCloud\Dds\V20151201\DescribeBackupDBs;
use think\Db;
use think\Exception;
use think\Model;

/**
 * 手牌模型
 * @package app\admin\model
 */
class HandCard extends Model
{
    protected $name = 'qt_hand_card';
    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    /**
     * 添加门票
     * @param $handCardName
     * @param $userInfo
     * @param $grantID
     * @return bool
     */
    public static function ticket($handCardName,$userInfo,$grantID){
        $handCardData = Db::name('qt_hand_card')->where(['store_id'=>$userInfo['store_id'],'name'=>$handCardName])->find();
        if($handCardData != null){
            $ticketData = Db::name('qt_admission_ticket')
                ->where("FIND_IN_SET(" . $handCardData['type'] . ",hand_cards)")
                ->find();
            if($ticketData != null){
                //计算金额并下单
                $goodsIds = explode(',',$ticketData['product_ids']);
                //手牌是否有订单
                $goodsOrderItem = Db::name('qt_product_order_item')->where(['hand_card_id'=>$handCardData['id'],'pay_status'=>'0'])->find();
                if(empty($goodsOrderItem)){
                    //创建总订单
                    $goodsOrderInsert = [
                        'order_no' => c_order_sn('2'),
                        'store_id' => $userInfo['store_id'],
                        'room_id' => '',
                        'engineer_id' => '',
                        'create_id' => $userInfo['id'],
                        'hand_card_id' => $handCardData['id'],
                        'total_price' => 0,
                        'content' => '',
                        'order_status' => '0',
                        'create_time' => time(),
                    ];
                    $goodsOrderId = Db::name('qt_product_order')->insertGetId($goodsOrderInsert);
                }else{
                    $goodsOrderId = $goodsOrderItem['order_id'];
                }
                $totalPrice = 0;
                $goodsRes = [];
                foreach ($goodsIds as $key=>$value){
                    $goodsData = Db::name('qt_goods')->where(['id'=>$value])->find();
                    $goodsRes[$key]['product_id'] = $value;
                    $goodsRes[$key]['num'] = 1;
                    $goodsRes[$key]['product_name'] = $goodsData['name'];
                    $goodsRes[$key]['product_price'] = $goodsData['price'];
                    $goodsRes[$key]['goods_total_price'] = $goodsData['price'];
                    $goodsRes[$key]['business_type'] = 1;
                    $totalPrice += $goodsData['price'];
                }
                try {
                    Db::startTrans();
                    //插入子订单
                    $orderItemModel = new ProductOrder();
                    $orderItemModel::saveProductOrderItem($goodsRes, $goodsOrderId, $userInfo, '');
                    //处理提成记录
                    $orderItemModel::saveCommissionLog($goodsOrderId, '');
                    //更新总订单金额
                    Db::name('qt_product_order')->where('id', $goodsOrderId)->setInc('total_price', $totalPrice['total_price']);
                    //更新手牌总金额
                    Db::name('qt_hand_grant')->where('id', $grantID)->setInc('money', $totalPrice['total_price']);
                    Db::commit();
                } catch (Exception $exception) {
                    Db::rollback();
                }
                return true;
            }
            return true;
        }
        return true;
    }


    /**
     * 检测手牌状态
     * @param $handCardId
     * @return bool
     */
    public static function checkStatus($handCardId){
        $data = self::get($handCardId);
        if($data['status'] == '2'){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 检测手牌最大消费数
     * @param $handCardId
     * @param $money
     * @return bool
     */
    public static function checkMaxMoney($handCardId,$money){
        $data = Db::name('qt_hand_card')
            ->alias('card')
            ->leftJoin('qt_hand_grant grant','grant.hand_card_id = card.id')
            ->where(['card.id'=>$handCardId])
            ->order('grant.id  desc')
            ->find();
        if($data == null){
            return false;
        }
        if($data['max_money'] != 0){
            if($data['max_money'] < ($data['money'] + $money)){
                return false;
            }else{
                return true;
            }
        }else{
            return true;
        }

    }


    /**
     * 检测手牌最大商品数
     * @param $handCardId
     * @param $money
     * @return bool
     */
    public static function checkMaxGoods($handCardId,$goodsId,$goodsNumber){
        $data = Db::name('qt_hand_card')
            ->alias('card')
            ->leftJoin('qt_hand_grant grant','grant.hand_card_id = card.id')
            ->where(['card.id'=>$handCardId])
            ->order('grant.id  desc')
            ->find();
        if($data == null){
            return false;
        }
        //查找已下单的商品
        $orderGoodsNumber = Db::name('qt_product_order_item')
            ->where(['hand_card_id'=>$handCardId,'pay_status'=>'0','status'=>'1','goods_id'=>$goodsId])
            ->sum('goods_num');
        $maxGoods = Db::name('qt_hand_goods')->where(['type'=>$data['type'],'product_id'=>$goodsId])->value('number');
        if($maxGoods == null){
            return true;
        }
        if(($goodsNumber + $orderGoodsNumber) > $maxGoods){
            return false;
        }
        return true;
    }




    /**
     * 根据手牌号返回金额
     * @param $handCardId
     * @return float
     */
    public static function checkMoney($handCardId){
        $projectMoney = Db::name('qt_order_project')->where(['hand_card_id'=>$handCardId,'pay_status'=>'0','is_delete'=>'2','is_change'=>'1'])->sum('price');
        $goodsMoney = Db::name('qt_product_order_item')->where(['hand_card_id'=>$handCardId,'pay_status'=>'0','status'=>'1'])->sum('goods_total_price');
        return $projectMoney + $goodsMoney;
    }

    /**
     * 减掉手牌的金额
     * @param $orderId
     * @param $handCardID
     * @param $type [1 项目 2 商品]
     */
    public static function decHandCardMoney($orderId,$handCardId,$type){
        if(empty($handCardId) || $handCardId == null){
            return true;
        }
        if($type == '1'){
            $projectMoney = Db::name('qt_order_project')
                ->where(['id'=>$orderId])
                ->value('price');
        }
        if($type == '2'){
            $projectMoney = Db::name('qt_product_order_item')
                ->where(['id'=>$orderId])
                ->value('goods_total_price');
        }
        $handGrandID = Db::name('qt_hand_grant')->where(['hand_card_id'=>$handCardId,'status'=>'2'])->order('id desc')->value('id');
        Db::name('qt_hand_grant')->where(['id'=>$handGrandID])->setDec('money',$projectMoney);
        return true;
    }


    /**
     * 获取手牌列表
     * @param $getData
     * @param $userInfo
     * @return array
     */
    public static function getList($getData,$userInfo){
        if(empty($getData['sort_type'])){
            return ['msg'=>'请选择排序方式','code'=>204];
        }
        if($getData['sort_type'] == '1'){
            $sort = 'hg.create_time desc';
        }else{
            $sort = 'hc.name asc';
        }
        $sql = Db::name('qt_hand_card')
            ->alias('hc')
            ->leftJoin('qt_hand_grant hg','hc.id = hg.hand_card_id')
            ->field('hc.id,hc.name,hc.status,hc.sort,hc.type,hg.money,hg.id as hand_grant_id,hg.room_id,hg.content,hg.marge')
            ->where(['hc.store_id'=>$userInfo['store_id']])
            ->whereIn('hg.status',['2','4']);
        //手牌类型筛选
        if(!empty($getData['type'])){
            $sql->where('hc.type',$getData['type']);
        }
        //手牌号
        if(!empty($getData['name'])){
            $sql->where('hc.name',$getData['name']);
        }
        //消费金额
        if(!empty($getData['money'])){
            $sql->where('hg.money','>',$getData['money']);
        }
        $data = $sql->order($sort)->select();
        foreach ($data as $key=>$value) {
            $grand = Db::name('qt_hand_grant')
                ->where([ 'hand_card_id' => $value['id']])
                ->whereIn('status',['2','4'])
                ->order('id desc')->find();
            $data[$key]['hand_grant_id'] = $grand['id'];
            $data[$key]['grant_time'] = $grand['create_time'];
            $data[$key]['grant_name'] = Db::name('qt_users')->where('id', $grand['grant_id'])->value('real_name');
            $data[$key]['project'] = Db::name('qt_order_project')
                ->where(['is_delete'=>2,'pay_status'=>'0','is_change'=>'1'])
                ->where('hand_card_id', $value['id'])
                ->column('name');
            $projectRoomName = Db::name('qt_order_project')
                ->alias('op')
                ->leftJoin('qt_room r','r.id = op.room_id')
                ->where('op.is_delete',2)
                ->where(['op.hand_card_id'=>$value['id'],'op.pay_status'=>'0','op.is_change'=>'1'])
                ->column('r.name');
            $margeHandCard = explode(',',$value['marge']);
            $handCardName = '';
            if(!empty($margeHandCard) && count($margeHandCard) > 1){
                $handCardIds = Db::name('qt_hand_grant')->whereIn('id',$margeHandCard)->column('hand_card_id');
                $handCardName = Db::name('qt_hand_card')->whereIn('id',$handCardIds)->column('name');
            }
            $data[$key]['marge_card_name'] = $handCardName;
            $projectCreateName = Db::name('qt_order_project')
                ->alias('op')
                ->leftJoin('qt_users u','u.id = op.created_order_id')
                ->where('op.is_delete',2)
                ->where(['op.hand_card_id'=>$value['id'],'op.pay_status'=>'0','op.is_change'=>'1'])
                ->column('u.real_name');

            $data[$key]['product'] = Db::name('qt_product_order_item')
                ->where(['hand_card_id'=>$value['id'],'pay_status'=>'0','status'=>'1'])
                ->column('goods_name');

            $goodsRoomName = Db::name('qt_product_order_item')
                ->alias('oi')
                ->leftJoin('qt_room r','r.id = oi.room_id')
                ->where(['oi.hand_card_id'=>$value['id'],'oi.pay_status'=>'0','oi.status'=>'1'])
                ->column('r.name');

            $goodsCreateName = Db::name('qt_product_order_item')
                ->alias('oi')
                ->leftJoin('qt_users u','u.id = oi.create_id')
                ->where(['oi.hand_card_id'=>$value['id'],'oi.pay_status'=>'0','oi.status'=>'1'])
                ->column('u.real_name');

            $roomName = array_merge($projectRoomName,$goodsRoomName);
            $roomName= array_unique($roomName);

            $createName = array_merge($projectCreateName,$goodsCreateName);
            $createName= array_unique($createName);
            $data[$key]['room'] = implode(',', $roomName);
            $data[$key]['create_name'] = $createName;

            $projectEngineerName = Db::name('qt_order_project')
                ->alias('op')
                ->leftJoin('qt_users u','u.id = op.engineer_id')
                ->where('op.is_delete',2)
                ->where(['op.hand_card_id'=>$value['id'],'op.pay_status'=>'0'])
                ->whereIn('op.status',[1,2])
                ->column('u.work_number');
            $data[$key]['work_number'] = implode(',',$projectEngineerName);
            $orderData = Db::name('qt_order_project')
                ->field('o.*,u.work_number')
                ->alias('o')
                ->leftJoin('qt_users u', 'u.id = o.engineer_id')
                ->where('o.is_delete',2)
                ->where(['o.hand_card_id' => $value['id'], 'o.is_change' => '1','pay_status'=>'0'])
                ->whereNotNull('o.engineer_id')
                ->order('o.id desc')
                ->find();
            if ($orderData == null && $value['status'] == '4') {
                $data[$key]['color'] = color($value['status']);
                $data[$key]['start_time'] = null;
                $data[$key]['end_time'] = null;
            } elseif($orderData != null) {
                $data[$key]['color'] = color($orderData['status']);
                $data[$key]['start_time'] = $orderData['start_time'];
                $data[$key]['end_time'] = $orderData['end_time'];
            }else{
                $data[$key]['color'] = 'rgb(255,255,255)';
                $data[$key]['start_time'] = null;
                $data[$key]['end_time'] = null;
            }
        }
        $result['user_number'] = Db::name('qt_hand_grant')
            ->where(['store_id'=>$userInfo])
            ->whereIn('status',['2','4'])
            ->count();
        $result['card_detail']= Db::name('qt_hand_card')
            ->field('count(card.id) as card_number,type.name')
            ->alias('card')
            ->leftJoin('qt_hand_card_type type','type.id = card.type')
            ->where(['card.store_id'=>$userInfo,'card.status'=>'2'])
            ->group('card.type')
            ->select();
        $result['man_project_number'] = Db::name('qt_order_project')
            ->alias('o')
            ->leftJoin('qt_project p','p.id = o.project_id')
            ->leftJoin('qt_hand_card c','c.id = o.hand_card_id')
            ->where(['c.status'=>'2','p.type'=>'1'])
            ->where('o.is_delete',2)
            ->count();
        $result['other_project_number'] = Db::name('qt_order_project')
            ->alias('o')
            ->leftJoin('qt_project p','p.id = o.project_id')
            ->leftJoin('qt_hand_card c','c.id = o.hand_card_id')
            ->where(['c.status'=>'2','p.type'=>'2'])
            ->where('o.is_delete',2)
            ->count();
        $result['list'] = $data;
        return ['msg'=>'查询成功','code'=>200,'data'=>$result];
    }


    /**
     * 加手牌的金额
     * @param $orderId
     * @param $handCardID
     * @param $type [1 项目 2 商品]
     */
    public static function incHandCardMoney($orderId,$handCardId,$type){
        if(empty($handCardId) || $handCardId == null){
            return true;
        }
        if($type == '1'){
            $projectMoney = Db::name('qt_order_project')
                ->where(['id'=>$orderId])
                ->value('price');
        }
        if($type == '2'){
            $projectMoney = Db::name('qt_product_order_item')
                ->where(['id'=>$orderId])
                ->value('goods_total_price');
        }
        $handGrandID = Db::name('qt_hand_grant')->where(['hand_card_id'=>$handCardId,'status'=>'2'])->order('id desc')->value('id');
        Db::name('qt_hand_grant')->where(['id'=>$handGrandID])->setInc('money',$projectMoney);
        return true;
    }


}
